package com.cms.entity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.cms.entity.base.BaseAdmin;
import lombok.EqualsAndHashCode;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 管理员表
 * </p>
 *
 * @author songfayuan
 * @since 2021-11-12
 */
@EqualsAndHashCode(callSuper = false)
@TableName("cms_admin")
public class Admin extends BaseAdmin {

    /** 角色 */
    @TableField(exist=false)
    @JSONField(serialize=false)
    private Role role;

    /**
     * 获取权限
     *
     * @return 权限
     */
    public List<String> getPermissions() {
        return JSONArray.parseArray(getRole().getPermission(), String.class);
    }

    /**
     * 获取角色
     *
     * @return 角色
     */
    public Role getRole(){
        if(role == null){
            Map<String,Object> map = SqlRunner.db().selectOne("select * from cms_role where id in (select roleId from cms_admin_role where adminId={0})",getId());
            role = JSON.parseObject(JSON.toJSONString(map), Role.class);
        }
        return role;
    }

    /**
     * 获取角色ID
     *
     * @return
     */
    public List<Integer> getRoleIds(){
        List<Object> roleIds = SqlRunner.db().selectObjs("select roleId from cms_admin_role where adminId={0}", getId());
        return roleIds.stream().map(i->Integer.parseInt(i.toString())).collect(Collectors.toList());
    }


}
